package com.lxujia.ruankao.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lxujia.ruankao.R;
import com.lxujia.ruankao.adapter.QuestionPagerAdapter;
import com.lxujia.ruankao.model.CategoryItem;
import com.lxujia.ruankao.model.QuestionItem;
import com.lxujia.ruankao.util.LogUtil;

import org.litepal.LitePal;

import java.util.List;

public class QuestionItemActivity extends RuanKaoBaseActivity {
    private final static String TAG = "QuestionItemActivity";
    private ViewPager mViewPager;
    private QuestionPagerAdapter mAdapter;
    private boolean mIsOnlyErrorQuestion = false;
    private int mCategoryItemId;
    private String mHeaderText;

    //第一道未做题 默认跳转
    private int mFirstItem = 0;
    /**
     * 信息提示
     *
     * @param context
     * @param msg
     */
    public static void showMessage(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);
        initViewPager();
    }

    /**
     * 初始化viewPager
     */
    private void initViewPager() {
        mViewPager = (ViewPager) findViewById(R.id.activity_question_detail_view_pager);

        Intent intent = getIntent();
        int categoryId = intent.getIntExtra("categoryId", -1);
        mIsOnlyErrorQuestion = intent.getBooleanExtra("isError", false);

        LogUtil.d(TAG, "initViewPager categoryId = " + categoryId);
        LogUtil.d(TAG, "initViewPager mIsOnlyErrorQuestion = " + mIsOnlyErrorQuestion);

        CategoryItem categoryItem = LitePal.find(CategoryItem.class, categoryId);

        if (categoryItem == null) {
            showMessage(this, "题目为空");
        }

        mCategoryItemId = categoryItem.getId();

        mHeaderText = categoryItem.getPeriodToShow() + "(" + categoryItem.getExtInfo() + ")";

        LogUtil.d(TAG, "questionItems end");
        mAdapter = new QuestionPagerAdapter(this, mHeaderText);
        mAdapter.setGotoNexCallback(new ViewPagerNextListener() {
            @Override
            public void GotoNextItem(boolean isRight) {
                int currentItem = mViewPager.getCurrentItem();
                int max = mAdapter.getCount() - 1;
                if (currentItem == max) { // 当前为最后一题
                    showResultDialog();
                } else if (isRight) { // 当前不是最后一题，且用户答案正确，跳到下一页
                    mViewPager.setCurrentItem(currentItem + 1);
                }
            }
        });
        loadQuestionItemData(mCategoryItemId);

        mViewPager.setAdapter(mAdapter);

        if (mFirstItem > 0 && mFirstItem < 74) {
            mViewPager.setCurrentItem(mFirstItem);
        }
    }

    public interface ViewPagerNextListener {
        public void GotoNextItem(boolean isRight);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.question_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mIsOnlyErrorQuestion) { // 隐藏 当前成绩 menu
            menu.findItem(R.id.action_current_result).setVisible(false);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.action_current_result:
                showResultDialog();
                break;
            case R.id.action_restart_category:
                restartCategory();
                break;
        }
        return true;
    }

    private void loadQuestionItemData(int categoryItemId) {
        String linkId = CategoryItem.class.getSimpleName().toLowerCase();
        String conditions = linkId + "_id == ?";
        if (mIsOnlyErrorQuestion) {
            conditions = conditions + " and isError == 1";
            setTitle(R.string.error_questions_category);
        }
        List<QuestionItem> questionItems = LitePal.where(conditions,
                String.valueOf(categoryItemId)).order("no asc").find(QuestionItem.class);

        if (questionItems == null || questionItems.size() == 0) {
            showMessage(this, "题目为空");
        }

        QuestionItem firstUndoItem = LitePal.where(conditions + " and userAnswer == -1",
                String.valueOf(categoryItemId)).order("no asc").findFirst(QuestionItem.class);
        if (firstUndoItem != null) {
            mFirstItem = firstUndoItem.getNo() - 1;
        }
        if (mAdapter != null) {
            mAdapter.setData(questionItems);
        }
    }

    private void restartCategory() {
        //所有题目变成 未做题，且是否错题 恢复为默认
        resetQuestionItemDb();

        loadQuestionItemData(mCategoryItemId);

        mViewPager.setCurrentItem(0);
    }

    private void resetQuestionItemDb() {
        ContentValues values = new ContentValues();
        values.put("userAnswer", -1);
        values.put("isError", 0);
        LitePal.updateAll(QuestionItem.class, values,
                "categoryitem_id == ?", String.valueOf(mCategoryItemId));
    }

    private void showResultDialog() {
        String errorConditions = "categoryitem_id == ?  and isError == 1";
        int errorCount = LitePal.where(errorConditions,
                String.valueOf(mCategoryItemId)).order("no asc").count(QuestionItem.class);

        String rightConditions = "categoryitem_id == ?  and isError != 1 and userAnswer != -1";
        int rightCount = LitePal.where(rightConditions,
                String.valueOf(mCategoryItemId)).order("no asc").count(QuestionItem.class);

        String notDoConditions = "categoryitem_id == ?  and userAnswer == -1";
        int notDoCount = LitePal.where(notDoConditions,
                String.valueOf(mCategoryItemId)).order("no asc").count(QuestionItem.class);

        LogUtil.d(TAG, "showResultDialog errorCount = " + errorCount
                + "; rightCount = " + rightCount + "; noDoCount = " + notDoCount);


        new MaterialDialog.Builder(this)
                .title(mHeaderText)
                .content("正确： " + rightCount + "    错误： " + errorCount + "    未做题： " + notDoCount)
                .positiveText("确定")
                .show();
    }
}
